<template>
  <div ref="warp" class="contentWarpBox">
    <div class="searchInfo">
      <div class="left">
        <el-input v-model="searchInfo.tittle" placeholder="请输入标题" style="width:120px;" clearable />
        <el-select
          v-model="searchInfo.identification"
          clearable
          placeholder="请选择直播标识"
          style="width:140px;"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="searchInfo.status" clearable placeholder="是否上架" style="width:120px;">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="searchInfoMation">搜 索</el-button>
      </div>
      <el-button
        v-if="accreditChildren.createLive"
        class="right"
        type="primary"
        @click="jump('create')"
      >新建直播</el-button>
    </div>
    <el-table ref="table" stripe :data="tableData" border :height="this.$getTableHeight">
      <el-table-column show-overflow-tooltip label="标题">
        <template slot-scope="scope">
          <span
            class="blue"
            @click.stop="changeActive(scope.row.id)"
          >{{ scope.row.id ? scope.row.tittle:'&nbsp;' }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="直播类型">
        <template
          slot-scope="scope"
        >{{ scope.row.liveType === 0 ? "公开课" :scope.row.liveType === 1 ?'非公开课':'' }}</template>
      </el-table-column>
      <el-table-column label="标签" width="175px">
        <template slot-scope="scope">
          <span v-if="scope.row.label">
            <el-tag
              v-for="tag in JSON.parse(scope.row.label)"
              :key="tag.id"
              :style="{color:'#'+tag.color}"
              :disable-transitions="false"
            >{{ tag.label }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="startTime" label="时间" />
      <el-table-column show-overflow-tooltip prop="historicalNumber" label="历史观看人数" />
      <el-table-column label="是否上架">
        <template
          slot-scope="scope"
        >{{ scope.row.status === true ? "是" : scope.row.status === false ?"否":'' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template slot-scope="scope">
          <div v-if="scope.row.id">
            <span v-if="scope.row.status">
              <span
                v-if="accreditChildren.startLive&&scope.row.identification === 0"
                class="_primary"
                @click="changeLiveStar(scope.row)"
              >开始直播</span>
              <span
                v-if="accreditChildren.startLive&&scope.row.identification === 1"
                class="_primary"
                @click="changeLiveStop(scope.row)"
              >结束直播</span>
            </span>
            <!-- <el-link
              icon="el-icon-edit"
              type="primary"
              style="margin-right: 15px;"
              @click="changeLiveQuestion(scope.row)"
            >直播问题</el-link>-->
            <span
              v-if="accreditChildren.deleteLive"
              class="_delete"
              @click="deleteInfo(scope.row)"
            >删除</span>
            <span class="_primary" @click="putLive(scope.row)">直播推送</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination clearfix">
      <Pagination
        class="right"
        :total-count="totalCount"
        :page-size="page.pageSize"
        :current-page="page.pageNo"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
    <div :class="active ? 'closeRightBox trans':'openRightBox trans'" @click.stop>
      <detail
        v-if="active"
        :id="jumpId"
        :accredit-children="accreditChildren"
        :page-height="pageHeight"
        :update-right="updateRight"
        @clearJumpId="clearJumpId"
        @editor="openDialog"
      />
    </div>
    <div v-if="dialogVisible" @click.stop>
      <el-dialog
        :title="isCreate ? '新建直播间' : '编辑直播间'"
        center
        :visible.sync="dialogVisible"
        width="800px"
        :close-on-click-modal="false"
        :before-close="handleClose"
      >
        <createAdver :id="jumpId" @closeDialog="handleClose" />
      </el-dialog>
    </div>
    <!--开始直播弹框-->
    <el-dialog
      title="创建直播"
      :visible.sync="createDialogVisible"
      width="800px"
      center
      :before-close="cancleCreateLive"
    >
      <el-form
        ref="editorLive"
        :model="editorLive"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="直播标题：" prop="tittle">
          <el-input v-model="editorLive.tittle" style="width:220px;" />
        </el-form-item>
        <el-form-item label="开始时间：" prop="startTime">
          <el-date-picker
            v-model="editorLive.startTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="时长：" prop="duration">
          <el-input v-model="editorLive.duration" style="width:220px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getAddress">获取播流地址</el-button>
        </el-form-item>
        <el-form-item v-if="playStream.push">
          <div v-loading="loading1">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>推流地址</span>
              </div>
              <li>{{ playStream.push }}</li>
            </el-card>
            <el-card class="box-card" style="marginTop:15px;">
              <div slot="header" class="clearfix">
                <span>播流地址</span>
              </div>
              <li
                v-for="(item,index) in playStream.play"
                :key="index"
                style="margin:5px 0 "
              >{{ item }}</li>
            </el-card>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleCreateLive">取 消</el-button>
        <el-button type="primary" @click="submitCreateLive">确 定</el-button>
      </span>
    </el-dialog>
    <!--结束直播弹框-->
    <!--直播问题弹框代码开始-->
    <el-dialog
      center
      title="直播问题"
      :visible.sync="showLiveQuestion"
      width="500px"
      :before-close="handleCloseQuestion"
    >
      <el-form label-width="100px">
        <el-form-item label="直播问题：">
          <div>
            <div v-for="(item,index) in questionArr" :key="index">
              <li v-if="item.status" style="cursor:pointer">
                <span @click="handleChangeList(item)">{{ item.content }}</span>
                <span class="right">
                  <i class="el-icon-delete hoverDeleteIcon" @click="deleteQuestion(item)" />
                </span>
              </li>
              <el-input
                v-else
                ref="saveTagInput"
                v-model="item.content"
                autofocus="true"
                class="input-new-tag"
                style="width:180px;"
                maxlength="80"
                @focus="handleChangeList(item)"
                @keyup.enter.native="handleInputListConfirm"
                @blur="handleInputListConfirm"
              />
            </div>
          </div>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            style="width:180px;"
            maxlength="80"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" @click="showInput">+ 添加问题</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseQuestion">取 消</el-button>
        <el-button type="primary" @click="handleSubmitQuestion">确 定</el-button>
      </span>
    </el-dialog>
    <!--直播问题弹框代码结束-->
    <div v-if="testDialogVisible">
      <el-dialog
        title="直播推送"
        :visible.sync="testDialogVisible"
        width="800px"
        center
        :before-close="putHandleClose"
      >
        <el-form ref="testDialog" :model="putInfoMation" :rules="rules" label-width="100px">
          <el-form-item label="推送标题" prop="tittle">
            <el-input v-model="putInfoMation.tittle"></el-input>
          </el-form-item>
          <el-form-item label="推送内容" prop="content">
            <el-input v-model="putInfoMation.content" rows="3" type="textarea" resize="none"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="testDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPutLive">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Pagination from "~/components/commom/pagination";
import createAdver from "~/components/live/create";
import detail from "~/components/live/detail";
import mmUrl from "~/utils/utilUrl";
import {
  trueOrFalse,
  randomRangeId,
  _currentChange,
  _sizeChange,
  _changeTable,
  _deleteMethods,
  _searchInfo,
  reduceArr,
  createDics,
  _getCurrentTime,
  changeTableHeight
} from "~/utils/util";
import initData from "~/utils/initData";

export default {
  components: {
    Pagination,
    createAdver,
    detail
  },
  data() {
    return initData.live;
  },
  mounted() {
    const pathStr = this.$route.path;
    this.initGetData();
    const result = JSON.parse(sessionStorage.getItem("menu"));
    this.accreditArr = reduceArr(result, "/" + this.$route.name);
    this.accreditChildren = createDics(
      this.accreditArr.children,
      "permissionCode"
    );
  },

  methods: {
    submitPutLive() {
      this.$refs['testDialog'].validate(valid => {
        if (valid) {
          this.$get({
            url: "/manage/live/sendLivePush",
            data: {
              liveId: this.PutLiveId,
              tittle: this.putInfoMation.tittle,
              content: this.putInfoMation.content
            }
          })
            .then(res => {
              this.$message({
                type: "success",
                message: res
              });
              this.testDialogVisible = false;
            })
            .catch(res => console.log(res));
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    putLive(res) {
      this.PutLiveId = res.id;
      this.testDialogVisible = true;
    },
    putHandleClose() {
      this.testDialogVisible = false;
    },
    handleClose() {
      this.dialogVisible = false;
      this.updateRight = !this.updateRight;
      this.searchInfoMation("no");
    },
    clearJumpId() {
      this.active = false;
      this.jumpId = null;
    },
    openDialog() {
      this.isCreate = false;
      this.dialogVisible = true;
    },
    changeActive(id) {
      this.active = true;
      this.jumpId = id;
    },
    jump(id) {
      this.dialogVisible = true;
      this.jumpId = id;
      id === "create" ? (this.isCreate = true) : (this.isCreate = false);
    },
    changeLiveStop(res) {
      this.$post({
        url: mmUrl.liveHistory.stop,
        data: {
          liveId: res.id
        }
      }).then(res => {
        this.$message({
          type: "success",
          message: res
        });
        this.searchInfoMation("no");
      });
    },
    handleSubmitQuestion() {
      this.$post({
        url: mmUrl.live.editor,
        data: {
          item: {
            id: this.questionNeedId,
            memberId: this.questionNeedMemberId
          },
          questionList: this.questionArr
        }
      }).then(() => {
        if (this.deleteArr.length) {
          this.$post({
            url: mmUrl.question.delete,
            data: {
              ids: this.deleteArr
            }
          }).then(() => {
            this.deleteArr = [];
          });
        }
        this.showLiveQuestion = false;
        this.$message({
          type: "success",
          message: "操作成功"
        });
      });
    },
    handleCloseQuestion() {
      this.showLiveQuestion = false;
    },
    changeLiveQuestion(res) {
      this.questionNeedId = res.id;
      this.questionNeedMemberId = res.memberId;
      this.showLiveQuestion = true;
      this.$post({
        url: mmUrl.live.loadEdit,
        data: {
          id: res.id
        }
      }).then(res1 => {
        this.editorLive = res1.item;
        this.editorLive.dataId = res1.item.id;
        res1.questions.forEach(v => {
          v.status = true;
        });
        this.questionArr = res1.questions;
      });
    },
    deleteQuestion(res) {
      trueOrFalse(this).then(() => {
        if (res.id) {
          this.deleteArr.push(res.id);
        }
        this.questionArr.forEach((v, index) => {
          if (v.id) {
            if (v.id === res.id) {
              this.questionArr.splice(index, 1);
            }
          } else if (v.jsId) {
            if (v.jsId === res.jsId) {
              this.questionArr.splice(index, 1);
            }
          }
        });
      });
    },
    handleChangeList(res) {
      res.status = false;
      this.questionArrIndex = res.id;
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      if (inputValue) {
        this.questionArr.push({
          content: inputValue,
          dataType: 1,
          status: true,
          dataId: this.liveId,
          jsId: randomRangeId(30)
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputListConfirm() {
      this.questionArr.forEach(v => {
        if (v.id === this.questionArrIndex) {
          v.status = true;
        }
      });
    },
    submitCreateLive() {
      this.editorLive.identification = 1;
      this.editorLive.startTime = _getCurrentTime();
      this.$refs["editorLive"].validate(valid => {
        if (valid) {
          this.$post({
            url: mmUrl.live.editor,
            data: {
              item: this.editorLive,
              questionList: []
            }
          }).then(() => {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.dialogVisible = false;
            this.searchInfoMation("no");
          });
        }
      });
    },
    cancleCreateLive() {
      this.$refs.editorLive.resetFields();
      this.createDialogVisible = false;
      this.playStream = {
        play: {},
        push: ""
      };
    },
    getAddress() {
      this.loading1 = true;
      this.$get({
        url: mmUrl.live.startLive,
        data: {
          dataId: this.editorLive.dataId
        }
      }).then(res => {
        this.loading1 = false;
        this.playStream = res;
      });
    },
    changeLiveStar(res) {
      this.liveId = res.id;
      this.createDialogVisible = true;
      this.$post({
        url: mmUrl.live.loadEdit,
        data: {
          id: res.id
        }
      }).then(res1 => {
        this.editorLive = res1.item;
        this.editorLive.dataId = res1.item.id;
        res1.questions.forEach(v => {
          v.status = true;
        });
        this.questionArr = res1.questions;
      });
    },
    deleteInfo(row) {
      const that = this;
      _deleteMethods(mmUrl.live.delelte, row, that).then(() => {
        that.searchInfoMation("no");
      });
    },
    searchInfoMation(res) {
      this.copySearchInfo = JSON.parse(JSON.stringify(this.searchInfo));
      const result = _searchInfo(res, this.page, this.copySearchInfo);
      this.changeTableData(result);
    },
    changeTableData(res) {
      const that = this;
      _changeTable(mmUrl.live.get, res, that);
    },
    handleSizeChange(val) {
      const result = _sizeChange(val, this.page, this.copySearchInfo);
      this.changeTableData(result);
    },
    handleCurrentChange(val) {
      const result = _currentChange(val, this.page, this.copySearchInfo);
      this.changeTableData(result);
    },
    initGetData() {
      const data = {};
      data.page = JSON.parse(JSON.stringify(this.page));
      Object.assign(data, this.copySearchInfo);
      this.$post({
        url: mmUrl.live.pageload,
        data: data
      }).then(res => {
        this.loading = false;
        this.tableData = res.items.items;
        this.totalCount = res.items.totalCount;
        changeTableHeight(this);
      });
    }
  }
};
</script>

<style lang="scss" module>
.margin3 {
  display: inline-block;
  padding-right: 10px;

  & > span {
    padding: 0 10px;
  }
}
</style>
